带有 () 的 C 对象 - 它有什么作用

C object with () - what does it do?

本文关键字:什么 作用 对象 带有      更新时间:2023-10-16

这段特定的代码是做什么的?更准确地说,什么是测试 tob((;做?

class test {
 private:
  int a;
  int b;
 public:
  test (int);
  test();
};
test::test() {
 cout<<"default";
}
test::test (int x=0) {
 cout<<"default x=0";
}
int main() {
 test tob();
}

我不知道测试 tob((; 做什么,但它没有给出任何编译错误。

test tob();

声明了一个返回类型为 test 的函数。它不会创建对象。它也被称为最令人烦恼的解析。

要创建test对象:

test tob;

此外,使用默认参数定义函数(包含构造器(的方式不正确。

test::test (int x=0) {  // incorrect. You should put it in function when it's first declared
 cout<<"default x=0";
}

下面的代码应该可以工作:

class test {
  int a;
  int b;
 public:
  explicit test (int = 0);    // default value goes here
};
test::test (int x) {          
 cout<<"default x=0";
}
int main() {
 test tob;    // define tob object
}