伙计们,我在C ++领域还很陌生,这是我的学期项目。当我在堆栈上创建IPADDRESS对象时,main.cpp文件将运行,直到为IPADDRESS对象调用了解构成员为止。第一部分运行正常,第二部分返回相同的输出,只是存在细分错误。
// Main file
#include <bits/stdc++.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include "IPInfo.h"
using namespace std;
// Function declaration of display()
void displayInfo(IPADDRESS);
int main(){
const char* address = "cbc.ca";
const char* command = "nslookup ";
char buf[256];
strcpy(buf, command);
strcat(buf, address);
string* Info = new(nothrow) string[256]; // Allocate 256 bytes to this string
*Info = system(buf); // Allocate the response from the command line to Info (which is on the heap)
cout << Info << endl << *Info << endl << "===============================" << endl << endl;
delete[] Info;
IPADDRESS test("cbc.ca");
displayInfo(test);
// Displays but never exits the program correctly
return 0;
}
void displayInfo(IPADDRESS Website){
string* displayBus;
displayBus = Website.getInfo();
cout << displayBus;
}
// Header file
#ifndef IPInfo_H
#define IPInfo_H
#include <bits/stdc++.h>
#include <string>
#include <iostream>
using namespace std;
class IPADDRESS{
private:
const char* command = "nslookup ";
string url;
string info;
string address;
int searchFor(string locator); // Find a substring in the getInfo string
public:
string* getInfo(); // Using the system("nslookup") call, get the info (Will be allocated to heap)
IPADDRESS(string website);
~IPADDRESS();
string getIPAddress(); // Using searchFor() get rid of unneeded characters and dump the IPAddress to a string
string getName(); // Also output the name
};
IPADDRESS::IPADDRESS(string website){
url = website;
}
IPADDRESS::~IPADDRESS(){
}
#endif
答案 0 :(得分:4)
这是不正确的
deleted
您不能也不应该IPADDRESS::~IPADDRESS(){
delete &address;
delete &url;
delete &info;
delete command;
}
delete
以外的任何变量。
默认的编译器生成的析构函数在此处已足够且正确(您可以将其完全删除,在这种情况下将隐式生成)。
new
答案 1 :(得分:1)
.et_pb_widget ul li {
background-color: #f9f9f9;
padding: 10px;
}
.et_pb_widget ul li:hover {
background-color: #EEEEEE;
color: #ff0000 !important;
}
.et_pb_widget > ul > li > a:hover {
background-color: #EEEEEE;
color: #ff0000 !important;
}
.et_pb_widget body:hover {
color:#ff0000;
}
用于释放通过delete
分配的内容,否则您不得使用它。
当前您发布的代码不包含new
,因此析构函数应为:
new
还请注意,如果使用动态内存分配,则应遵循The Rule of Three。 最好避免在C ++中进行裸露的动态内存分配。