gpt4 book ai didi

C++ 变量 - 声明和定义。遗产

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:32:43 27 4
gpt4 key购买 nike

让我们有一个 C++ 对象 A。A 中有两个变量(VAR1 和 VAR2)可供其子对象访问。对象 B 扩展了 A 并有一个私有(private)变量 VAR3,它还可以访问 VAR1 和 VAR2。 A/B 的每个实例都有自己的变量。

这是声明和定义变量的正确方法吗?

啊啊


class A {
protected:
static std::string const VAR1;
static std::string VAR2;
};

A.cpp


#include "A.h"
using namespace std;
string const A::VAR1 = "blah";
string A::VAR2;

B.h


#include "A.h"
class B : public A {
private:
static std::string VAR3;

public:
B(std::string const v1, std::string const v2);
void m() const;
};

B.cpp


#include "B.h"
using namespace std;

string B::VAR3;

B::B(string const v1, string const v2) {
VAR2 = v1;
VAR3 = v2;
}

void B::m() const {
// Print VAR1, VAR2 and VAR3.
}

最佳答案

Each instance of A/B has its own variables.

Would this be the right way of declaring and defining the variables?

没有。您已将 A 的成员声明为 static,这意味着它们是类变量,而不是实例变量。每个实例都没有得到它自己的拷贝。相反,它们都共享同一个实例。

使非静态:

class A {
protected:
std::string const VAR1;
std::string VAR2;
};

... 然后,当然,您不需要全局初始化器,所以去掉这个:

string const A::VAR1 = "blah";
string A::VAR2;

...并且如果您希望 VAR1 每次实例化 A 时都有一个默认值,那么您可以在类的初始化列表(或在ctor body ,如果你是朋克 :) ):

A::A() : VAR1("blah") {};

关于C++ 变量 - 声明和定义。遗产,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4854503/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com