C ++未解析的外部符号 [英] C++ unresolved external symbol

查看:393
本文介绍了C ++未解析的外部符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨iam begginer在c ++我有类的静态方法,我无法访问它,它抛出一个错误

Hi iam begginer at c++ i have class with static methods and i cant access them it throws me an error

    1>------ Build started: Project: CPractice, Configuration: Debug Win32 ------
1>  Source.cpp
1>Source.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > CPractice::name" (?name@CPractice@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A)
1>c:\users\innersoft\documents\visual studio 2012\Projects\CPractice\Debug\CPractice.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

这里是我的代码

#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <string>

using namespace std;

class CPractice
{
    public:
        static void setName(string s)
        {
            name = s;
        }
        static string getName()
        {
            return name;
        }
    private:
        static string name;
};


int main()
{


    CPractice::setName("Name");
    cout << "\n" << CPractice::getName();
    system("PAUSE");
    return EXIT_SUCCESS;
}


推荐答案

static string name;

由于 static 声明 name - 您还需要定义它。只需将它放在类定义下:

As it is static, this line only declares name - you need to define it too. Simply place this below your class definition:

string CPractice::name;

如果你最终将类移动到相应的头文件和实现文件,在实现文件中。它只能在一个翻译单元中定义。

If you end up moving your class to a corresponding header and implementation file, make sure you place this definition in the implementation file. It should only be defined in a single translation unit.

这篇关于C ++未解析的外部符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆