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

标签 c++ variables scope declare

让我们有一个 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/

相关文章:

c++ - GStreamer 在 Qt5 树莓派中遇到一般流错误

c++ - 如何声明一个类显式抽象?

c++ - 总和不会在此数组类型代码中正确打印出来

swift - '? :' 表达式中的结果值的类型不匹配 'String.SubSequence' (又名 'Substring' )和 'String'

javascript - 如何在它自己的方法调用中引用 jQuery 对象?

c - 为什么不需要释放静态数组?

c++ - gsl::span - 指向结束的指针

c++ - makefile 命令在第一个目标之前开始

PHP 不将变量传递给其他页面

ruby-on-rails-3 - 如何获取rails 3中所有数据库行的范围?