我無法訪問已在指針數組中創建的對象。我有一些測試代碼顯示對象正在創建,但在我的ShowCluster()
函數中,它通過第二級循環的第一次迭代掛起。無法訪問在指針數組中創建的對象
我相信我有它編碼的方式是,我有一個Node **對象,實質上成爲一個二維數組。由於我使用的是new
運算符,因此我不必擔心函數內部的範圍。
關於爲什麼我不能顯示我創建的這些對象的內容的任何想法。這只是我想用來幫助我理解指針的玩具代碼。
Main.cpp的
#include <iostream>
#include "Node.h"
void Test(std::string message){
static int testNumber = 0;
std::cout << "[+] Test: " << testNumber << " : " << message << std::endl;
testNumber++;
}
void Default2dNodeArray(Node** myCluster, int height, int width, int vecLength){
Test("Start of array creation.");
myCluster = new Node*[height];
for(int i=0; i<height; i++){
myCluster[i] = new Node[width];
}
Test("End of array creation.");
}
void ShowCluster(Node **myCluster, int height, int width){
Test("Start of Display array.");
for(int i=0; i<height; i++){
Test("Outer for loop");
for(int j=0; j<width; j++){
Test("Inner for loop");
std::cout << myCluster[i][j].myNodeString << " : " << myCluster[i][j].myNodeInt << std::endl;
}
}
Test("End of Display array.");
}
int main(){
int myHeight = 5;
int myWidth =8;
int myVecLength = 4;
Node** myNodeArray;
std::cout << "Starting pointer test" << std::endl;
Test("In main.");
Default2dNodeArray(myNodeArray, myHeight, myWidth, myVecLength);
Test("In main.");
ShowCluster(myNodeArray, myHeight, myWidth);
Test("In main.");
std::cout << "Ending pointer test" << std::endl;
return 1;
}
Node.cpp
#include "Node.h"
#include <stdlib.h>
#include <stdio.h>
#include <sstream>
#include <iostream>
int Node::globalCounter = 0;
Node::Node(){
std::cout << "Node created." << std::endl;
std::stringstream ss;
ss << "Default: " << globalCounter;
myNodeString = ss.str();;
myNodeInt = globalCounter;
myVecLength = new int[3];
globalCounter++;
}
Node::Node(std::string myString, int myInt, int vecLength){
myNodeString = "Non-Default:" + myString;
myNodeInt = globalCounter;
myVecLength = new int[vecLength];
globalCounter++;
}
Node.h
#ifndef NODE_H_
#define NODE_H_
#include <string>
class Node {
public:
static int globalCounter;
std::string myNodeString;
int myNodeInt;
int* myVecLength;
Node();
Node(std::string, int, int);
};
#endif /* NODE_H_ */
http://markgodwin.blogspot.com/2009/08/c-reference-to-pointer.html – NDEthos 2014-11-03 22:00:48