C++变量 - 声明和定义。遗产
让我们有一个 C++ 对象 A。A 中有两个变量(VAR1 和 VAR2)可供其子对象访问。 对象 B 扩展了 A 并具有一个私有变量 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;
Bh
#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.
}
Let's have a C++ object A. There are two variables (VAR1 and VAR2) in A accessible to its children.
Object B extends A and has one private variable VAR3 it can also access VAR1 and VAR2. Each instance of A/B has its own variables.
Would this be the right way of declaring and defining the variables?
A.h
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.
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不。您已将
A
的成员声明为static
,这意味着它们是类变量,而不是实例变量。每个实例都没有自己的副本。相反,它们都共享同一个实例。然后使之成为非
静态
:...然后,当然,您不需要全局初始化程序,因此摆脱此:
...如果您想要
VAR1
每次实例化A
时都有一个默认值,那么您可以在类的初始化列表中执行此操作(或者在 ctor 主体中,如果您是朋克:) ):No. You've declared
A
's members asstatic
which means they are class-variables, not instance-variables. Each instance doesn't get it's own copy. Instead, they all share the same instance.Make then non-
static
:... and then, of course, you don't need the global initializer so get rid of this:
...and if you want
VAR1
to have a default value every timeA
is instantiated, then you can do that in the class' initializer list (or in the ctor body, if you're a punk :) ):A/B 的每个实例都有自己的变量。
事实并非如此。您已将它们声明为
静态
。停止这样做,您可能会更接近您想要的结果。Each instance of A/B has its own variables.
Not so. You've declared them
static
. Stop doing that and you might get closer to your desired result.不,你搞错了。
A
和B
的数据声明为static
呢?No, you got it wrong.
A
andB
's data asstatic
?