我是新来的,所以我希望我能写出可以理解的问题。
我的问题是,如何使用重载运算符()访问类中的静态数组。
Main.cpp:
class SomeClass
{
public:
static const int a[2][2];
const int& operator() (int x, int y) const;
};就在它下面,我定义了数组a:
const int SomeClass::a[2][2] = {{ 1, 2 }, { 3, 4 }};下面是重载操作符:
const int& SomeClass::operator() (int x, int y) const
{
return a[x][y];
}在main()中,我想通过使用SomeClass(1, 1)来访问'a‘2D数组,它应该返回4。但是当我尝试像这样编译main时:
int main(void)
{
cout << SomeClass(1, 1) << endl;
return 0;
}我得到了这个错误:
PretizeniOperatoru.cpp: In function ‘int main()’:
PretizeniOperatoru.cpp:22:22: error: no matching function for call to ‘Tabulka::Tabulka(int, int)’
PretizeniOperatoru.cpp:22:22: note: candidates are:
PretizeniOperatoru.cpp:5:7: note: SomeClass::SomeClass()
PretizeniOperatoru.cpp:5:7: note: candidate expects 0 arguments, 2 provided
PretizeniOperatoru.cpp:5:7: note: SomeClass::SomeClass(const SomeClass&)
PretizeniOperatoru.cpp:5:7: note: candidate expects 1 argument, 2 provided我意识到我不知道,问题出在哪里。似乎有一个叫做类的构造器。看起来我是在构造类而不是访问数组。
什么意思?有没有像这样做数组的方法,或者打破封装规则并将其定义为全局会更好?这是否意味着重载操作符不能用于访问静态数组?
当我这样做的时候,它编译正常:
int main(void)
{
SomeClass class;
cout << class(1, 1) << endl;
return 0;
}感谢您的回复,希望我的问题有意义。我没有使用[]运算符进行访问,因为它比( )更难实现。
发布于 2011-10-20 01:47:56
你需要实例化你的类的对象来访问它的成员。尝试使用
cout << SomeClass()(1, 1) << endl;相反,实例化一个临时变量并使用它的运算符()。
发布于 2011-10-20 01:48:19
您不能创建静态operator()。语法SomeClass(1, 1)正在尝试调用SomeClass的不存在的构造函数,该构造函数接受两个整数。您必须有一个要调用operator()的对象实例,就像您在第二个示例中所做的那样(除了class是一个关键字)。
发布于 2011-10-20 01:49:22
您不能重载操作符并使其成为静态的。
也就是说,您可以重载运算符并从SomeClass类型的对象访问成员
SomeClass s;
s(1,2);https://stackoverflow.com/questions/7825618
复制相似问题