问题描述
你好,我是C ++的新手,我想知道我是否可以创建一个带有函数的struct / class来操作该类中的数据。例如,我有以下内容:
Hello, I am fairly new to C++ and I was wondering if I can make a struct/class with a function in that to manipulate data within that class. For example I have the following:
#include <sys/stat.h>
#include <fstream>
namespace ByteReader
{
public class IO
{
public:
struct Stream
{
long length;
long position;
unsigned char* data;
};
struct stat results;
int fileSize(char* filepath)
{
if (stat(filepath, &results) == 0)
return results.st_size;
else
return 0;
}
};
}
我试图从微软为一个小应用程序重新创建System :: IO :: Stream类我正在制作。我想将流设置为like并将readInt32等函数放入struct / class中。这可能吗?另外我如何将文件路径作为参数传递给类?
ie:
ByteReader :: IO br = new ByteReader :: IO(文件路径);
I was trying to recreate the System::IO::Stream class from microsoft for a little app I''m making. I would like to have the stream setup like and have functions such as ReadInt32 into the struct/class. Is that possible to do? Also how would I pass a filepath as an argument in the class?
ie:
ByteReader::IO br = new ByteReader::IO( filepath );
推荐答案
class IO{
public:
IO(const char* filePath){_filePath=filePath;};
private:
const char* _filePath;
};
方法的重点是对类本身进行操作。
我认为你应该多做一些阅读。构造函数实际上是基本的东西。
The whole point of methods is to do manipulations on the class itself.
I think you should do some more reading. A constructor is really elementary stuff.
this->myField = myMethodParameter;
这将使用method参数或其他任何内容修改实例的字段 myField
其他领域。
请看我过去的回答: []。
你看,我只回答你的标题问题,如解决方案1.解决方案基本上是正确但不完整。你对重新创造的猜测是完全不清楚的;我怀疑他们是基于一些误解,但我无法弄清楚到底是什么,对不起。
This will modify the instance''s field myField
using the method parameter, or anything else, say, some other field.
Please see my past answer: Catch 22 - Pointers to interface objects die when function using them is made static.[^].
You see, I just respond only to your question of the title, as in Solution 1. That solution is basically correct but incomplete. You speculations about "re-creation" are completely unclear; I suspect they are based on some misconception, but I cannot figure out what exactly, sorry.
这篇关于具有空白/功能的类或结构? C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!