小编asr*_*att的帖子

返回成员变量时,为什么在函数内外得到不同的结果?

当我尝试在函数内部打印成员变量时,它会给出我想要的结果.但是,如果我返回此成员变量然后尝试在main中访问它,它会给我一个不同的结果.为什么会这样?

这是我的代码的样子:

Node.h:

#include <cstddef>
#include <vector>
#include <iostream>

using namespace std;

class Node{
 public:
    int v;
    Node * parent;
    Node(int I);
    Node(int I,Node * p);
    vector<Node*> myfun();
}
Run Code Online (Sandbox Code Playgroud)

Node.cpp:

Node::Node(int I){
    v = I;
    parent = NULL;
}

Node::Node(int I,Node * p){
    v = I;
    parent = p;
}

vector<Node*> Node::myfun(){
    vector<Node*> myvec;

    Node next1(1,this);
    myvec.push_back(&next1);

    Node next2(2,this);
    myvec.push_back(&next2);

    cout << myvec[0]->v << endl; // prints out "1"
    cout << myvec[1]->v << endl; // prints out "2"

    return(myvec);
} …
Run Code Online (Sandbox Code Playgroud)

c++ pointers return function vector

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

C/C++ 中的 float* 和 float[n] 有什么区别

使用有什么区别

float* f;
Run Code Online (Sandbox Code Playgroud)

float f[4];
Run Code Online (Sandbox Code Playgroud)

或者他们的处理方式完全相同?使用一个而不是另一个可能会导致您遇到内存分配问题吗?如果没有,是否有任何情况下他们被区别对待?

不知道这是否相关,但我使用类型 float* 作为函数参数。例如:

void myfun(float* f){
     f[0] = 0;
     f[1] = 1;
     f[2] = 2;
     f[3] = 3;
}
Run Code Online (Sandbox Code Playgroud)

它编译并运行良好(我不确定为什么 - 我认为因为我没有分配任何内存f,它会抛出某种异常)。

c pointers static-memory-allocation

-4
推荐指数
1
解决办法
431
查看次数

标签 统计

pointers ×2

c ×1

c++ ×1

function ×1

return ×1

static-memory-allocation ×1

vector ×1