- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
让我们有一个 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/
我的应用程序上有一个登录系统,其中有一组预定义的用户,如下所示: User user = new User("tommy", "tommy", false); User user2 = new Use
我厌倦了以下问题。请帮忙?我有一个下面的界面 /** * Type of Timestamp. For ex: Date, long, Calendar etc * */ public interf
这里没有问题,只需要解释它是如何工作的。 我正在为我的 C# 类(class)做家庭作业,我设法按照教授提供的代码示例自行完成。问题是我不明白它是如何工作的。以下是让我感到困惑的事情: 首先,为什么我
class C1 { void A(); void B(); } void C1::A(){ return B(); } class C2 : public C1 { void
我有一组代码,它模拟了一个基本的图书馆编目系统。有一个名为 items 的基类,其中定义了通用 id、title 和 year 变量以及其他 3 个派生类(DVD、Book 和 CD)。 基础[元素]
似乎无法弄清楚这一点。我一直收到各种错误,所以我只用我从 Jackson 那里收到的当前错误来写这篇文章。 public class ResponseDetail { private Resp
我希望继承一些 D 类遗产并实现接口(interface) A、B 和 C 的所有属性和方法。请帮我举一个 Delphi 中的示例。 我用德尔福 Xe7 一个类如何实现多个接口(interface)?
看看我的问题: 我有一个如下所示的类: var els=[]; var base = function(){ this.config = {} } var X1 = function(){ }
我正在学习如何编写好的 Makefile。我必须编写几个 gcc 编译命令,这些命令会生成使用不同选项编译的不同文件。我读过有关 .SECONDEXPANSION 的内容,但它不太令我满意,因为它看起
我有很多不同的课程。但是,它们都可以保证具有某些方法,例如render()和Activate()。 我的目标是能够将它们全部存储在一个大列表中。目前,我有一个名为Container的大类,并且我做了类
让我们有一个 C++ 对象 A。A 中有两个变量(VAR1 和 VAR2)可供其子对象访问。对象 B 扩展了 A 并有一个私有(private)变量 VAR3,它还可以访问 VAR1 和 VAR2。
例如,我创建了一个鸟类类,我正在尝试创建一个 boolean 变量,它开始时不快乐,当它飞行时变为快乐,当它尝试游泳时又变回不快乐。 这是我的鸟类 public class Bird extends
我也有一个关于如何在两个类之间创建复制构造函数的问题。 > person(const person& a) : name(a.getName()), address(a.getAddress()),
好吧,这个例子对于我试图理解的概念来说非常简单明了。我将向您展示代码: class Base { protected: string name; public: virtual str
首先,我不太确定如何为我的问题命名。 我有一个关于继承的问题。 假设我创建了一个名为 Class_A 的类: class Class_A { public: int a;
我一直在谷歌上搜索和阅读相关内容,但还没有找到答案,也许有人可以帮我解决这个问题。 我希望我的 UserPile 类能够从我的 CardPile 类访问数据成员和类成员函数。我不断收到标题中提到的错误
假设我在一个类中有一些数据结构如下 class DataStructure { DataStructure(); ~DataStructure(); void reset();
我是一名优秀的程序员,十分优秀!