-
Oct 8th, 2019, 04:47 AM
#1
Thread Starter
Lively Member
Define the name of an object in a class based on a string value in C++
I have a class as stated below. What I want to do is to assign the class a value based on a string value (the string is called sObject), like below. How do I do that?
Code:
#include <iostream>
#include <fstream> //for reading csv file I believe
#include <bits/stdc++.h> //for classes
using namespace std;
class Category
{
// Access specifier
public:
// Data Members
string sCategory;
// Member Functions()
void printname(){
cout << "Category is: " << sCategory;
}
};
int main(){
string sObject
sObject= "BMW"
// Declare an object of class
Category sObject;
// accessing data member
sObject.sCategory = "3 series";
// accessing member function
sObject.printname();
}
-
Oct 9th, 2019, 06:42 AM
#2
Re: Define the name of an object in a class based on a string value in C++
In c++ classes and class instances do not have 'a value'. The class member variables for each object instance of a class contain data for that instance. So in this case, sObject is a class instance of Category and has it's sCategory member variable set to 3 series. However the proceeding attempt to assign the value BMW to sObject is invalid as sObject itself cannot have a value. The make either needs to be stored as another member of Category, or you could create another class called something like Manufacturer (which has a member variable to hold the manufacturer's name) and derive class Category from that.
Depending upon what you are trying to do, a multi-map may be better.
All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/
C++23 Compiler: Microsoft VS2022 (17.6.5)
-
Oct 9th, 2019, 06:46 AM
#3
Thread Starter
Lively Member
Re: Define the name of an object in a class based on a string value in C++
Ok, thanks. I'll try a map instead!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|