标签: const

const在C++函数体中

我意识到,如果我将const int定义到c ++函数体中然后使用地址算法来改变常量的值(它在堆栈上,不是吗?).我有这个代码:

const int a = 10;
int b = 100;

int * c = &b;
c++;

cout << "&a: " << &a << endl;
cout << " c: " << c << endl;


*c = 100500;

cout << " a: " << a << endl;
cout << "*c: " << *c << endl;
Run Code Online (Sandbox Code Playgroud)

我得到了这个输出

&a: 0x7ffff63866a8
c: 0x7ffff63866a8

 a: 10
*c: 100500
Run Code Online (Sandbox Code Playgroud)

因此,地址是相同的,但值是不同的.有人能解释一下这个结果吗?谢谢!ps我试过GCC,Clang和VS.

c++ const point-of-interest

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

初始化时具有非恒定大小的字符数组

我需要在C++ char数组中初始化非常量大小.大小必须是非常量的,因为它是从函数生成的,不能使用向量,因为这个char数组将用于读取和写入文件.例:

int i = functionToGetvalue();
unsigned char ch[i];
file1 >> ch;
file2 << ch;
Run Code Online (Sandbox Code Playgroud)

c++ arrays initialization const

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

c ++虚函数总是必须是const?

我只是想知道所有虚函数是否必须是const?

我遇到了一些问题,因为当我打算将它们打印出来时,该区域总是为我的方块返回0.如果有人能够启发我,我将不胜感激.

shapetwod.h

class ShapeTwoD
{
    protected:
        string name, warpSpace;
        bool containsWarpSpace;
    public:
        //constructor
        ShapeTwoD();
        ShapeTwoD(string, bool);

        //accessors/set function
        void setName(string);

        //mutator/get function
        string getName();



        //methods
        virtual double computeArea();
        virtual void view();
};
Run Code Online (Sandbox Code Playgroud)

shapetwod.cpp

ShapeTwoD::ShapeTwoD()
{
    string name = "";
}

ShapeTwoD::ShapeTwoD(string ShapeName)
{
    name = ShapeName;
}

void ShapeTwoD::setName(string shapeName)
{
    name=shapeName;
}

string ShapeTwoD::getName()
{
    return name;
}

double ShapeTwoD::computeArea()
{
    return 0;
}

void ShapeTwoD::view()
{
    cout << "Area is: " << endl;
}
Run Code Online (Sandbox Code Playgroud)

square.h

class Square:public …
Run Code Online (Sandbox Code Playgroud)

c++ virtual const

-6
推荐指数
1
解决办法
338
查看次数

const struct {x} vs struct {const x}

这是一个相当简单的问题,但不知何故很难找到一个简单的答案.

在C++中,(编辑)const修改的结构变量和(编辑:)非const结构变量之间的区别是什么,但结构具有所有const成员?:

typedef struct mystruct {
    const int x;
} t1;
const t1 s1;
Run Code Online (Sandbox Code Playgroud)

VS

typedef struct {
    int x;
} t2;
const t2 s2;
Run Code Online (Sandbox Code Playgroud)

?(如果答案是"与课程相同",那么请为课程解释或链接到解释.)

c++ struct const constants

-7
推荐指数
2
解决办法
1363
查看次数

为什么之后不能设置const指针?

我知道这可能是一个微不足道的问题.在声明之后无法设置const指针的逻辑是什么?这并不是说分配内存会改变const引用的起始地址.那么为什么不能......

int* const p;
p = new int [10];
Run Code Online (Sandbox Code Playgroud)

...完成...这也禁止将const指针传递给函数?

c++ pointers const function

-8
推荐指数
1
解决办法
623
查看次数