如果我只在类内部使用类变量,为什么要在类外部创建类变量的定义呢?
Why have I to create the definition of the class variables out of the class, if I use them only inside?
尝试创建一个小测试,我遇到了一个问题
#include "stdafx.h"
#include "CppUnitTest.h"
#include "CppUnitTestAssert.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace SprintfTestNamespace
{
TEST_CLASS(SprintfTest)
{
public:
static char output[100];
static const char * expected;
TEST_METHOD_INITIALIZE(SprintfTestInit)
{
memset(output, 0xaa, sizeof output);
SprintfTest::expected = "";
}
static void expect(const char * s)
{
expected = s;
}
static void given(int charsWritten)
{
Assert::AreEqual((int)strlen(expected), charsWritten,
L"result string length ");
Assert::AreEqual(expected, output, false,
L"result string content ");
Assert::AreEqual((char)0xaa, output[strlen(expected) + 1],
L"meaning of the first outer char after string");
}
TEST_METHOD(NoFormatOperations)
{
expect("hey");
given(sprintf(output, "hey"));
}
TEST_METHOD(InsertString)
{
expect("Hello Worldn");
given(sprintf(output, "Hello %sn", "World"));
}
};
char SprintfTest::output[100]; // notice these two lines!
const char* SprintfTest::expected;
}
如果我删除最后的两个标记行,我得到错误LNK2001:
未解析的外部符号"public: static char * SprintfTestNamespace::SprintfTest::output" (?output@SprintfTest@ sprintftestnamespace@2pada)
如果我有他们的地方,一切工作正常,它构建和链接和测试。但是,如果我只在类内使用类变量,为什么我要在类外定义它们呢?
您没有在类外声明它们。您正在在类外定义它们。在c++中,作为左值使用的对象需要一个定义,这实际上是为该对象保留存储空间(内存)。对于静态类成员,可以通过在类外定义这样的对象来保留内存。
类内部的只是这些静态成员的非定义性声明。为这些声明提供定义是您的责任。当您忘记定义您声明的东西时,您将从链接器获得"未解析的外部符号…"错误,这正是您的情况所发生的。
请注意,为了满足一个定义规则,这些定义通常应该进入单个实现文件(.cpp
文件)。你不应该把这样的定义放在头文件中。
相关文章:
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 无法在具有常量变量大小的类中创建堆栈分配数组
- 正在头类中为私有变量创建内联函数
- 在 android 上从 Java 调用C++类方法或函数,而无需在每次调用时重新创建类/变量
- C 将在类中创建的线程共享同一类变量
- 如何创建派生指针类变量
- 尝试使用自定义类的结构中的变量创建该类的优先级队列
- 有没有办法在C++基类中创建一个"virtual"变量?
- 更改构造函数中每个创建的对象的类变量
- 在另一个类中创建一个静态类变量,使用已删除的函数 = 错误
- 创建函数来访问类变量是一种好的做法吗
- 创建类变量时内存泄漏
- 如何在继承类中创建父类变量数组作为私有成员
- 如果我只在类内部使用类变量,为什么要在类外部创建类变量的定义呢?
- 创建子类变量的语法
- 在类中创建静态变量(c++)
- 如何创建一个类变量数组
- 如何创建不同大小的数组作为私有类变量
- 在c++中创建对象作为私有类变量
- 在类中创建运算符+而不声明太多不必要的变量的最佳方法