C ++在方法中传递const字符串引用?

时间:2009-11-23 21:32:58

标签: c++ methods const

我正在尝试初始化我的Class的私有变量,并将const字符串& aString作为参数传递给它。

这是我的方法:

void Image::initWithTextureFile(const std::string &inTextureName)
{   
    Texture2D *imTexture = TEXTURE_MANAGER->createTexture(inTextureName);

    if(imTexture)
    {
        texture = imTexture;
        scale = 1.0f;
        name = inTextureName; //name is a private string variable inside my class
        initImplementation();
    }else {
        printf("Could not load texture when creating Image from file %s\n",inTextureName.c_str());
    }
}

我的问题如下,当我调用此方法时,我会这样做:

myInitializer.initWithTextureFile("myFile.bmp");

当我在initWithTextureFile范围内时,name变量的值为inTextureName。对于此示例,如果cout << name << endl;内的initWithTextureFile我将获得"myFile.bmp"

但是当我离开函数的范围时,name会丢失它的值,所以当我cout << name << endl;时,我在控制台中没有打印任何内容。

有人能指出我在这里发生了什么吗?

声明姓名:

private:
    std::string name;

8 个答案:

答案 0 :(得分:3)

您要么省略说明中的内容,要么没有显示有助于解决问题的相应代码。

这有效:

#include <iostream>
#include <string>

using namespace std;

struct A
{
    void f(const string& str) { name = str; }
    void g() { cout << name << endl; }

    string name;
};

int main()
{
    A a;
    a.f("test");
    a.g();
}

输出:

test

答案 1 :(得分:3)

如果你在课堂范围之外,并且cout << name完全编译,则意味着你有另一个名为name的变量,这就是被拾取的内容。如果你想在课外引用它,你必须想出一种方法来导出它。例如,您可能拥有类似const std::string &GetName() { return name; }的成员函数。

答案 2 :(得分:1)

那应该有用。你确定它没有被其他地方修改,比如在initImplementation中吗?

答案 3 :(得分:0)

问题可能与name变量有关:它是指针还是引用字符串而不是普通字符串?

答案 4 :(得分:0)

这里唯一合理的解释是你必须使用两个不同的name个对象。当您退出方法时,您声明为类成员的那个应该保持其值。只是在类方法之外,您必须打印一个完全不同的name,这是空的。

答案 5 :(得分:0)

我打算谈一下短暂的堆栈对象,但我意识到这是错误的。可能是从DLL导出包含类的事情。

如果是这样,您可能会发现如下警告:

c:\yourclass.h(7): warning C4251: 'YourClass::name_' : class 'std::basic_string<_Elem,_Traits,_Ax>' needs to have dll-interface to be used by clients of class 'YourClass'

This thread描述了更多内容。

答案 6 :(得分:-1)

如何宣布'姓名'?似乎它可能被声明为引用而不是对象。

答案 7 :(得分:-1)

尝试:

name = std::string(inTextureName);