小编Rik*_*ken的帖子

C-Style字符串到std :: string转换澄清

我有几个问题,我认为对于有C++经验的人来说很容易回答,我会大胆提出TL的问题; DR

给出以下代码:

void stringTest(const std::string &s)
{
    std::cout << s << std::endl;
}

int main()
{
    stringTest("HelloWorld");
}
Run Code Online (Sandbox Code Playgroud)

希望有人可以在我的思考过程中指出错误:

为什么在传递C-Style字符串时stringTest中的参数必须标记为const?是不是存在使用其cstyle字符串构造函数发生的std :: string的隐式转换,因此"s"不再是对文字的引用(并且不需要是const).

此外,cstyle字符串构造函数看起来是什么样的,编译器如何知道在看到它时调用它:

stringTest("HelloWorld");
Run Code Online (Sandbox Code Playgroud)

它是否只是将字符串文字识别为char*?

在研究复制构造函数时,我偶然发现了这些问题.我自己澄清的另一个快速问题......

在类似的情况下:

std::string s = "HelloWorld";
Run Code Online (Sandbox Code Playgroud)

用于实例化临时std :: string的cstyle字符串构造函数,然后使用字符串复制构造函数将临时字符串复制到"s"中吗?:

std::string(const std::string&);
Run Code Online (Sandbox Code Playgroud)

c++ string copy

5
推荐指数
1
解决办法
709
查看次数

访问违规写入静态全局变量?

给出以下代码:

#include "stdafx.h"
#include "string.h"
static char *myStaticArray[] = {"HelloOne", "Two", "Three"};

int _tmain(int argc, _TCHAR* argv[])
{
    char * p = strstr(myStaticArray[0],"One");
    char hello[10];
    memset(hello,0,sizeof(hello));
    strncpy(hello,"Hello",6);
    strncpy(p,"Hello",3); // Access Violation
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试写入myStaticArray [0]的地址时,正在获得访问冲突.为什么这是个问题?

背景:我将旧的C++移植到C#主要是C#开发人员,所以请原谅我的无知!这段代码显然不是旧版本中的问题,所以我很困惑......

c string

1
推荐指数
1
解决办法
852
查看次数

如何在运行时确定对象的基础类型?

鉴于以下代码块:

class BaseClass
{
public:
    virtual void hello() { cout << "Hello from Base" << endl; }
};

class DerivedClass : public BaseClass
{
public:
    void hello() { cout << "Hello from Derived" << endl; }
};

int main()
{
    BaseClass base;
    DerivedClass derv;

    BaseClass* bp = &base;
    bp->hello();
    bp = &derv;
    bp->hello();
}
Run Code Online (Sandbox Code Playgroud)

bp指向的类型在运行时是如何确定的?我知道它是动态绑定的,但是这样做的机制是什么? 我很困惑,因为通常的答案是编译器,但因为它是动态的,它不是在这个例子的情况下(或者是我错了?我想编译器这件事的时间提前,但什么表明,BP现在指向一个DerivedClass?).我也来自C#,所以这个想法对我来说很陌生,因为这是没有CLR的本机代码.

c++ oop polymorphism inheritance object

0
推荐指数
1
解决办法
78
查看次数

标签 统计

c++ ×2

string ×2

c ×1

copy ×1

inheritance ×1

object ×1

oop ×1

polymorphism ×1