小编Jib*_*bel的帖子

为什么在类作用域中定义变量的顺序并不重要?

如果我们在任何函数中执行这两行,我们都会得到一个错误,这是合乎逻辑的,因为变量b是在初始化之后定义的a = b

int a = b;
int b = 0;
Run Code Online (Sandbox Code Playgroud)

但是当我们将这两行插入到类的作用域中时,为什么类不关心定义的顺序呢b

class Foo
{
    int a = b;
    int b = 0;
};
Run Code Online (Sandbox Code Playgroud)

c++ variables scope initialization

8
推荐指数
3
解决办法
469
查看次数

构造函数与“=”运算符执行相同的操作吗?

  1. 当我们没有定义任何=运算符时,编译器如何知道使用构造函数?
  2. 构造函数不是只在定义变量时调用吗?
#include <string>

class Person
{
public:
    std::string name;
    Person(const char* fullName) : name(fullName) {}
};

int main()
{
    Person p1("Jibel Sadeghi"); // This is ok because we declared the constructor with a const char*
    /* When we didn't overload the '=' operator for 'const char*',
       how the next lines don't have any errors? */
    p1 = "Ben Sadeghi";
}
Run Code Online (Sandbox Code Playgroud)

c++ oop constructor operator-overloading assignment-operator

0
推荐指数
1
解决办法
176
查看次数